<template>
    <a-row style="height: 100%">
        <!-- 笔记本栏 -->
        <a-col :span="3" style="background-color: #313640">
            <!-- 头部 -->
            <a-page-header class="ant-page-header-notebook" title="笔记本">
                <template #extra>
                    <!-- 删除笔记本图标 -->
                    <MinusOutlined @click="removeNotebook"
                        style="color: red;cursor: pointer;font-size: 16px;margin-right: 5px;vertical-align: middle;" />
                    <!-- 添加笔记本图标 -->
                    <PlusOutlined @click="showAddNotebookModalForm"
                        style="color: yellow; cursor: pointer; font-size: 16px;vertical-align: middle;" />
                </template>
            </a-page-header>
            <a-divider />
            <!-- 笔记本列表 -->
            <a-menu id="notebook" mode="inline" v-model:selectedKeys="selectedKeys" @select="selectHandle"
                style="background-color: #313640;max-height: calc(100vh - 120px);min-height: calc(100vh - 115px);overflow: hidden auto;">
                <a-menu-item :key="notebook" v-for="notebook in notebooks">
                    <template #icon>
                        <FolderOpenOutlined />
                    </template>
                    <span>{{ notebook }}</span>
                </a-menu-item>
            </a-menu>
            <!-- 底部同步按钮 -->
            <div style="display: flex; justify-content: center;">
                <a-button type="primary" shape="round" size="small" @click="syncToCloud"
                    style="height: 25px;padding: 2px 3px;margin: 0 2px;font-size: 9px;">
                    <template #icon>
                        <CloudUploadOutlined style="vertical-align: middle;font-size: 9px;" />同步到云端
                    </template>
                </a-button>
                <a-button shape="round" size="small" @click="downToLocal"
                    style="height: 25px;padding: 2px 3px;margin: 0 2px;font-size: 9px;color: #fff;background: #36870e;border-color: #36870e;">
                    <template #icon>
                        <DownloadOutlined style="vertical-align: middle;font-size: 9px;" />同步到本地
                    </template>
                </a-button>
            </div>
        </a-col>

        <!-- 笔记栏 -->
        <a-col :span="5" style="background-color: #f4f5f6">
            <!-- 头部 -->
            <a-page-header title="笔记">
                <template #extra>
                    <!-- 删除笔记图标 -->
                    <MinusOutlined @click="removeNote"
                        style="color: red;cursor: pointer;font-size: 16px;margin-right: 15px;vertical-align: middle;" />
                    <!-- 添加笔记图标 -->
                    <PlusOutlined @click="newNote"
                        style="color: #52c41a; cursor: pointer;font-size: 16px;vertical-align: middle;" />
                </template>
            </a-page-header>
            <a-divider />
            <!-- 笔记列表 -->
            <a-list item-layout="horizontal" :data-source="notes">
                <template #renderItem="{ item }">
                    <a-list-item>
                        <a-list-item-meta @click="noteSelect(item.title)">
                            <template #title>
                                <a>{{ item.title }}</a>
                            </template>
                        </a-list-item-meta>
                    </a-list-item>
                </template>
            </a-list>
        </a-col>

        <!-- 编辑器栏 -->
        <a-col :span="16">
            <div v-if="showMdEditor">
                <a-form layout="inline">
                    <a-form-item style="width: 99.5%; margin: 0 auto; padding: 1px 0">
                        <a-input class="mdtitle-input" v-model:value="mdTitle" placeholder="文章标题"></a-input>
                    </a-form-item>
                </a-form>
                <v-md-editor v-model="mdText" height="94vh" @save="saveMdText"></v-md-editor>
            </div>
        </a-col>
    </a-row>

    <!-- 添加笔记本弹出表单 -->
    <a-modal title="添加笔记本" okText="确认" cancelText="取消" v-model:visible="addNotebookModalFormVisible"
        :confirm-loading="confirmLoading" @ok="addNotebookOk">
        <a-form layout="inline">
            <a-form-item label="笔记本名称">
                <a-input v-model:value="newNotebookName" placeholder="笔记本名称"></a-input>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script>
import { defineComponent, reactive, toRefs, onMounted, createVNode } from "vue";
import { message, Modal } from "ant-design-vue";
import {
    PlusOutlined,
    MinusOutlined,
    FolderOpenOutlined,
    ExclamationCircleOutlined,
    CloudUploadOutlined,
    DownloadOutlined,
} from "@ant-design/icons-vue";

import { invoke } from '@tauri-apps/api/tauri'

export default defineComponent({
    components: {
        PlusOutlined,
        MinusOutlined,
        FolderOpenOutlined,
        // ExclamationCircleOutlined,
        CloudUploadOutlined,
        DownloadOutlined,
    },
    setup() {
        const data = reactive({
            notebooks: [], // 笔记本列表
            notes: [], // 笔记列表
            selectedKeys: [], // 笔记本选中项key
            currentNotebook: "", // 当前选中笔记本
            currentNote: "", // 当前选中笔记
            notEditedMdtext: "", // 未编辑的文章内容
            showMdEditor: false, // 是否显示编辑器
            newNotebookName: "", // 新建笔记本的名称
            addNotebookModalFormVisible: false, // 是否显示添加笔记本表单
            confirmLoading: false, // 添加笔记表单等待状态（是否转圈圈）
            newNoteMdFileName: "", // 新建的笔记文件名
            mdTitle: "", // 文章标题
            mdText: "", // 文章内容Markdown格式
        });

        // 笔记本被选中(打开笔记本)
        const selectHandle = ({ key }) => {
            //   console.log("key", key);
            // console.log("selectedKeys", selectedKeys);

            // 暂存前一个选中的笔记本
            var oldSelectNotebook = data.currentNotebook;

            // 临时创建的笔记且内容为空，在切换到其他笔记本时，直接删除临时笔记
            if (key != oldSelectNotebook && (!data.mdText) && /\d{14}/.test(data.mdTitle)) {
                // console.log('删除临时笔记');
                invoke('remove_temp_note', { currentNotebook: data.currentNotebook, currentNote: data.currentNote })
                    .then(res => {
                        if (res && res.code == 200) {
                            data.mdTitle = '';
                            data.mdText = '';
                        }
                    }).catch(err => {
                        console.log(err);
                    });
            }

            // 判断是否有未保存的文章
            if (
                key != oldSelectNotebook &&
                data.mdText &&
                data.mdText != data.notEditedMdtext
            ) {
                // 有未保存的文章
                Modal.confirm({
                    title: () => "编辑器有文章未保存，确认丢弃吗?",
                    icon: () => createVNode(ExclamationCircleOutlined),
                    content: () => "",
                    okText: () => "确认",
                    okType: "danger",
                    cancelText: () => "取消",
                    onOk() {
                        // 点击了确认按钮
                        data.mdText = "";
                        data.showMdEditor = false;
                        data.currentNote = "";
                        message.info("已丢弃", 1);
                    },
                    onCancel() {
                        // 点击了取消按钮
                        data.currentNotebook = oldSelectNotebook;
                        data.selectedKeys = [oldSelectNotebook];
                        message.info("操作取消", 1);
                        return;
                    },
                });
            }
            data.currentNotebook = key;
            data.currentNote = "";

            // 调用方法获取笔记本下的全部笔记
            invoke('get_note_list', { notebook: key }).then(res => {
                if (res && res.code == 200) {
                    // console.log(res.data);
                    var tem = res.data;
                    data.notes = tem.map(n => {
                        return { title: n }
                    });
                } else {
                    message.error("获取数据失败：" + res.msg);
                }
            }).catch(err => {
                console.log(err);
            });
        };

        // 笔记被选中(打开笔记)
        const noteSelect = (noteTitle) => {
            // console.log("笔记被点击：", noteTitle);
            data.currentNote = noteTitle;
            // 调用方法读取本地保存的笔记
            // console.log('调用方法读取本地保存的笔记');
            invoke('read_note_file', { currentNotebook: data.currentNotebook, noteTitle: noteTitle }).then(res => {
                if (res && res.code == 200) {
                    var tem = res.data;
                    data.mdText = tem;
                    data.notEditedMdtext = tem; // 原始笔记内容
                    data.mdTitle = noteTitle;
                    data.showMdEditor = true;
                } else {
                    message.error("读取失败：" + res.msg);
                    message.info(`请点击 "同步到本地" 后再打开该笔记`);
                }
            }).catch(err => {
                console.log(err);
            });
        };

        // 显示添加笔记本对话框
        const showAddNotebookModalForm = () => {
            data.addNotebookModalFormVisible = true;
        };

        // 添加笔记本表单点击确认按钮
        const addNotebookOk = () => {
            var notebookName = data.newNotebookName.trim();
            data.confirmLoading = true;
            // 创建笔记本
            invoke('create_notebook', { notebookName: notebookName }).then(res => {
                if (res && res.code == 200) {
                    message.success("笔记本创建成功", 1);
                    data.notebooks.push(notebookName);
                    data.currentNotebook = notebookName; // 当前笔记本为新建的
                    data.selectedKeys = [notebookName]; // 选中新建的笔记本
                    data.newNotebookName = ""; // 清空
                    data.addNotebookModalFormVisible = false; // 隐藏表单
                } else {
                    message.error("笔记本创建失败：" + res.msg);
                }
                data.confirmLoading = false; // 停止转圈圈
            }).catch(err => { console.log(err); });
        };

        // 添加笔记(临时笔记)
        const newNote = () => {
            var notebook = data.currentNotebook;
            if (notebook) {
                console.log('调用方法添加笔记');
                invoke('create_note_file', { notebook: notebook }).then(res => {
                    if (res && res.code == 200) {
                        message.success("笔记创建成功：" + fileName, 1);
                        var fileName = res.data;
                        data.newNoteMdFileName = fileName;
                        console.log('newNoteMdFileName == ', fileName);
                        data.notes.push({ title: fileName });
                        data.currentNote = fileName;    // 置当前笔记为新建的临时笔记
                        // 打开该临时笔记
                        data.mdTitle = fileName;
                        data.mdText = '';
                        data.showMdEditor = true;
                    } else {
                        message.error("笔记创建失败：" + res.msg);
                    }
                }).catch(err => { console.log(err); });
            }
        };


        // 保存文章/笔记
        const saveMdText = (mdText) => {
            // console.log(mdText);
            if (data.mdTitle == '' || /^\d+$/.test(data.mdTitle)) {    // 标题为空
                message.error('请输入标题', 2);
                return;
            }
            if (/^\d+$/.test(data.mdTitle)) {    // 标题为临时文件名
                message.error('请输入新标题', 2);
                return;
            }
            if (data.currentNotebook && data.currentNote) { // 不为空
                // 调用保存笔记方法
                invoke('save_note', {
                    currentNotebook: data.currentNotebook,
                    currentNote: data.currentNote,
                    mdTitle: data.mdTitle,
                    mdText: mdText
                }).then(res => {
                    if (res && res.code == 200) {
                        message.success("笔记保存成功", 1);

                        // 重新获取笔记列表
                        invoke('get_note_list', { notebook: data.currentNotebook }).then(res => {
                            if (res && res.code == 200) {
                                var tem = res.data;
                                data.notes = tem.map(n => {
                                    return { title: n }
                                });
                            } else {
                                message.error("获取数据失败：" + res.msg);
                            }
                        }).catch(err => {
                            console.log(err);
                        });

                    } else {
                        message.error('笔记保存失败：' + res.msg);
                    }

                }).then(err => { console.log(err); })

            } else {  // 存在为空情况
                message.error('请选定笔记本和笔记');
            }
        }

        // 删除笔记本
        const removeNotebook = () => {
            if (data.currentNotebook) {
                Modal.confirm({
                    title: () => `确认删除笔记本 "${data.currentNotebook}" 吗？`,
                    content: () => '删除笔记本，其中的笔记文件也将一并删除！',
                    icon: () => createVNode(ExclamationCircleOutlined),
                    okText: () => '删除',
                    okType: 'danger',
                    cancelText: () => '取消',
                    onOk() {
                        // 点击了确定，开始删除
                        invoke('remove_notebook',
                            {
                                currentNotebook: data.currentNotebook,
                            }).then(res => {
                                if (res && res.code == 200) {
                                    message.success("操作成功");
                                    data.currentNotebook = "";
                                    // 重新获取笔记本列表数据
                                    invoke('get_local_notebooks')
                                        .then((res) => {
                                            if (res && res.code == 200) {
                                                data.notebooks = res.data;
                                            } else {
                                                message.error("获取数据失败：" + res.msg);
                                            }
                                        })
                                        .catch((err) => {
                                            message.error("获取数据失败：" + err);
                                        });
                                } else {
                                    message.error("操作失败：" + res.msg);
                                }
                            }).catch(err => { console.log(err); });

                    },
                    onCancel() {
                        message.info('取消操作', 1);
                    },
                });
            } else {
                message.info('请选中要删除的笔记本', 1);
            }
        }

        // 删除笔记
        const removeNote = () => {
            if (data.currentNotebook == '' || data.currentNote == '') {
                message.error('请选择笔记');
                return;
            }
            Modal.confirm({
                title: () => `确认删除笔记 "${data.currentNotebook} \\ ${data.currentNote}" 吗？`,
                icon: () => createVNode(ExclamationCircleOutlined),
                okText: () => '删除',
                okType: 'danger',
                cancelText: () => '取消',
                onOk() {
                    // 点击了确定，开始删除
                    invoke('remove_note',
                        {
                            currentNotebook: data.currentNotebook,
                            currentNote: data.currentNote
                        }).then(res => {
                            if (res && res.code == 200) {
                                message.success("操作成功");
                                data.currentNote = "";
                                // 重新获取笔记列表数据
                                invoke('get_note_list', { notebook: data.currentNotebook }).then(res => {
                                    if (res && res.code == 200) {
                                        var tem = res.data;
                                        data.notes = tem.map(n => {
                                            return { title: n }
                                        });
                                    } else {
                                        message.error("获取数据失败：" + res.msg);
                                    }
                                }).catch(err => {
                                    console.log(err);
                                });

                            } else {
                                message.error("操作失败：" + res.msg);
                            }
                        }).catch(err => { console.log(err); });
                },
                onCancel() {
                    message.info('取消操作', 1);
                },
            });
        }

        // 同步到云端
        const syncToCloud = () => {
            console.log('同步到云端');
        }

        // 同步到本地
        const downToLocal = () => {
            console.log('同步到本地');
        }

        // 生命周期，挂载完毕
        onMounted(() => {
            // console.log('获取笔记本数据');
            // 获取笔记本数据
            invoke('get_local_notebooks')
                .then((res) => {
                    if (res && res.code == 200) {
                        data.notebooks = res.data;
                    } else {
                        message.error("获取数据失败：" + res.msg);
                    }
                })
                .catch((err) => {
                    message.error("获取数据失败：" + err);
                });
        });

        return {
            ...toRefs(data),
            selectHandle,
            noteSelect,
            showAddNotebookModalForm,
            addNotebookOk,
            newNote,
            saveMdText,
            removeNotebook,
            removeNote,
            syncToCloud,
            downToLocal,
        };
    },
});
</script>

<style>
.ant-page-header-notebook {
    padding: 16px 18px !important;
}

.ant-page-header-heading-left {
    margin: 0 !important;
}

.ant-page-header-heading-title {
    color: #1890ff !important;
}

.ant-divider-horizontal {
    margin: 0 !important;
}

#notebook {
    border: none !important;
}

.ant-menu-title-content {
    color: white !important;
    /* padding: 0 15px !important; */
    font-weight: 500 !important;
}

.ant-menu:not(.ant-menu-horizontal) .ant-menu-item-selected {
    background-color: #49565c !important;
}

.ant-list-item-meta {
    cursor: pointer;
}

.ant-list-item-meta:hover {
    background-color: #ccc;
}

.ant-list-item-meta-content {
    cursor: pointer;
}

.ant-list-item-meta-content:hover {
    background-color: #ccc;
}

.ant-list-item {
    padding: 6px 0 !important;
}

.ant-list-item-meta-title {
    margin-bottom: 0 !important;
    padding: 0 5px !important;
    font-size: 15px !important;
}

.ant-list-item-meta-title a {
    vertical-align: middle !important;
}

.ant-list-items {
    overflow: hidden auto !important;
    max-height: calc(100vh - 80px) !important;
    min-height: calc(100vh - 80px) !important;
}

.mdtitle-input {
    border: 1px solid !important;
    border-top: none !important;
    border-left: none !important;
    border-right: none !important;
    border-bottom-color: blueviolet !important;
}
</style>